package models

import "github.com/astaxie/beego/orm"

type AttachType struct {
	Id   int64  `json:"id"`
	Name string `json:"name"`
}

func AttachTypeList() ([]*AttachType, int64) {
	sortorder := "Id"
	query := orm.NewOrm().QueryTable("tp_attach_type")
	data := make([]*AttachType, 0)
	total, _ := query.Count()
	_, _ = query.OrderBy(sortorder).All(&data)
	return data, total
}

func SaveAttachType(m *AttachType) (int64, error) {
	o := orm.NewOrm()
	if m.Id == 0 {
		id, err := o.Insert(m)
		if err != nil {
			return 0, err
		} else {
			m.Id = id
		}
	} else {
		if _, err := o.Update(m); err != nil {
			return 0, err
		}
	}
	return m.Id, nil
}

func DelAttachType(m *AttachType) error {
	o := orm.NewOrm()
	err := o.Begin()
	_, err = o.QueryTable("tp_attach_type").Filter("id", m.Id).Delete()
	if err == nil {
		_, err = o.QueryTable("tp_attach").Filter("type", m.Id).Update(orm.Params{
			"type": 0,
		})
	}

	if err == nil {
		err = o.Commit()
	} else {
		err = o.Rollback()
	}
	return err
}
